package com.lianyou.chapter02.containerelement.typeCascaded;

import jakarta.validation.ConstraintViolation;
import jakarta.validation.Valid;
import jakarta.validation.Validation;
import jakarta.validation.Validator;
import jakarta.validation.executable.ExecutableValidator;

import java.lang.reflect.Method;
import java.util.Set;

/**
 * @Author: wangzhen
 * @Date: 2024-08-30 15:02
 * @Version: v1.0.0
 * @Description: TODO
 **/
public class Controller {

    public Result<@Valid Room> test1(){
        Room room = new Room();
        room.name = "YourBatman";
        Result<Room> result = new Result<>();
        result.setData(room);
        return result;
    }


    public static void main(String[] args) throws Exception {
        //  会报错, 他不认识这个容器
        //excludeValueExtractor();

        includeValueExtractor();
    }

    public static void excludeValueExtractor() throws NoSuchMethodException {
        Validator validator = Validation.buildDefaultValidatorFactory()
                .usingContext()
                .getValidator();

        ExecutableValidator executableValidator = validator.forExecutables();

        Method test1 = Controller.class.getMethod("test1");

        Room room = new Room();
        room.name = "YourBatman";
        Result<Room> result = new Result<>();
        result.setData(room);
        Set<ConstraintViolation<Controller>> constraintViolations = executableValidator.validateReturnValue(new Controller(), test1, result);

        if (!constraintViolations.isEmpty()){
            constraintViolations.stream().forEach(Object::toString);
        }
    }

    public static void includeValueExtractor() throws NoSuchMethodException {
        Validator validator = Validation.buildDefaultValidatorFactory()
                .usingContext()
                .addValueExtractor(new ResultValueExtractor())
                .getValidator();

        ExecutableValidator executableValidator = validator.forExecutables();

        Method test1 = Controller.class.getMethod("test1");

        Room room = new Room();
        room.name = "YourBatman";
        room.setFinished(false);
        // 这里  和方法的  返回值必须都写成这样
        Result<@Valid Room> result = new Result<>();
        result.setData(room);
        Set<ConstraintViolation<Controller>> constraintViolations = executableValidator.validateReturnValue(new Controller(), test1, result);

        if (!constraintViolations.isEmpty()){
            constraintViolations.stream().forEach(t->{
                System.out.println(t.getMessage());
                System.out.println(t.getPropertyPath());
            });
        }
    }
}
